箭头函数和普通函数有什么区别
主要是 this 的差别,箭头函数里面的 this 是外面的 this。
普通函数
const obj = {
a: 1,
fn: function () {
console.log(this.a) // 1
}
}
箭头函数 因为箭头函数里面的 this 是外面的 this,所以 fn()里的 this 指向到全局 Window,而 Window 中没有 a 属性,所以返回 undefined
const obj = {
a: 1,
fn: () => {
console.log(this.a) // undefined
}
}
普通函数转箭头函数
因为箭头函数里面的 this 是外面的 this,所以 fn()里的 this 指向到全局 Window,让_this 等于 this 实际上还是指向到全局 Window,因为指向同一对象,所以 fn()里的 this 可以替换成_this
var _this = this
var obj = {
a: 1,
fn: function fn() {
console.log(_this.a) //_this为全局window
}
}